package com.dyrnq.seckill.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {

    // 10 days
    private static final long EXPIRATION_TIME = 864_000_000;
    private static final String TOKEN_HEADER = "Bearer ";

    public static String generateToken(String username, Map<String, ?> map, String secret) {

        byte[] keyBytes = Decoders.BASE64.decode(secret);
        Key key = Keys.hmacShaKeyFor(keyBytes);

        return Jwts.builder()
                .subject(username)
                .claims(map)
                .issuer("seckill")
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(key)
                .compact();
    }

    public static String createKey() {
        //Key key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        Key key = Jwts.SIG.HS512.key().build();
        return Encoders.BASE64.encode(key.getEncoded());
    }

    public static Claims parseJwt(String token, String secret) {
        if (token != null && token.startsWith(TOKEN_HEADER)) {
            token = token.substring(TOKEN_HEADER.length()).trim();
        }
        byte[] keyBytes = Decoders.BASE64.decode(secret);
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);
        try {
            return Jwts.parser()
                    .verifyWith(key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (ExpiredJwtException ex) {
        } catch (Throwable e) {
            log.warn(e.getMessage(), e);
        }

        return null;
    }
}
